package com.chatplus.application.web.security;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.digest.DigestUtil;
import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;

public class Md5PasswordEncoder implements CompatiblePasswordEncoder {
    private static final String LEGACY_PASSWORD_SALT = "123qwe";

    @Override
    public boolean isSupport(String encodedPassword) {
        //MD5的摘要长度为固定的128bit 16字节
        if (StringUtils.length(encodedPassword) != 32) {
            return false;
        }
        try {
            byte[] bytes = HexUtil.decodeHex(encodedPassword);
            return bytes.length == 16;
        } catch (Exception e) {
            //encodedPassword不是有效的Hex字符串
            return false;
        }
    }

    @Override
    public String encode(CharSequence rawPassword) {
        return DigestUtil.md5Hex(rawPassword + LEGACY_PASSWORD_SALT);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return MessageDigest.isEqual(DigestUtil.md5(rawPassword + LEGACY_PASSWORD_SALT), HexUtil.decodeHex(encodedPassword));
    }
}
